import React, { Component } from 'react';
import { connect } from 'dva';
import './index.less';
import classNames from 'classnames';
import { Toast, Modal, Button, List } from 'antd-mobile';
import { CSSTransition } from 'react-transition-group';
import { encrypt, fetchApi } from '@/utils/utils';
import router from 'umi/router';
import { randomNum } from '@/utils/index';
import { baseUrl } from '@/utils/baseServer';
import { authenticateSuccess } from '@/utils/session';

// @connect(({ login }) => ({ login }))

const LOGIN_STATUS = {
  LOGIN: 1,
  REGISTER: 2,
};
class LoginNew extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      code: '',
      phone: '', // 电话
      phoneIsFocus: false, // 是否获取焦点
      phoneError: false, // 电话是否格式错误
      imgCode: '', // 图形验证码
      imgCodeIsFocus: false, // 是否获取焦点
      imgCodeError: false, // 图形验证码是否图形错误
      password: '', // 短信验证码
      passwordIsFocus: false, // 是否获取焦点
      codeText: '获取验证码',
      isWait: false, // 是否在倒计时
      codeImageUrl: '', // 验证码图片
      visible: false,
      isLoginBtn: true,
      passwordCheck: '', //密码确认
      passwordCheckIsFocus: false, // 是否获取焦点
    };
  }

  componentDidMount() {
    this._createCode();
    this.testApi();
  }
  // 协议弹窗
  showProtocol() {
    this.setState({
      visible: true,
    });
  }
  close(v) {
    this.setState({
      visible: false,
    });
  }
  onClose = key => () => {
    this.setState({
      [key]: false,
    });
  };

  //test api
  async testApi() {
    let res = await fetch('api/video/list?id=16&pageSize=10&pageNo=1', {
      method: 'get',
    });
    console.log(res, 'res');
  }

  // 注册
  register = async params => {
    let res = await fetchApi('web/register', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });
    console.log(res);
    if (res.status === 0) {
      Toast.success('注册成功', 1);
      this.setState({
        isLoginBtn: true,
      });
    } else {
      Toast.fail(res.message, 1);
      this._createCode();
    }
  };

  // 登陆
  login = async params => {
    let res = await fetchApi('web/login', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });
    console.log(res);
    if (res.status === 0) {
      Toast.success('登陆成功', 1);
      localStorage.setItem('phone', res.data.phone);
      authenticateSuccess(res.data.token);
      router.push('/home');
    } else {
      Toast.fail(res.message, 1);
      this._createCode();
    }
  };
  /**
   * 刷新图形验证码
   */

  /**
   * 倒计时
   */
  setTime() {
    this.setState({ isWait: true });
    let countdown = 60;
    this.setState({ codeText: countdown + 's' });
    this.timer = setInterval(() => {
      if (countdown === 0) {
        this.setState({
          codeText: '重新获取',
          isWait: false,
        });
        this.refreshCodeImage();
        clearInterval(this.timer);
      } else {
        countdown--;
        this.setState({ codeText: countdown + 's' });
      }
    }, 1000);
  }

  /**
   * 获取短信验证码
   *  @return {Boolean} 当信息不完整时退出
   *

  /**
   * 登录
   * @return {Boolean} 当信息不完整时退出
   */
  submit = type => {
    const { isLoginBtn } = this.state;
    if (type === LOGIN_STATUS.LOGIN && isLoginBtn === true) {
      // 直接验证登陆
      let checkStatus = this.checkData();
      if (!checkStatus) return;
      const { phone, password } = this.state;
      this.login({ phone, password: encrypt(password) });
    } else if (type === LOGIN_STATUS.LOGIN && isLoginBtn === false) {
      this.setState({
        isLoginBtn: true,
      });
      this._createCode();
    } else if (type === LOGIN_STATUS.REGISTER && isLoginBtn === false) {
      let checkReStatus = this.checkData(LOGIN_STATUS.REGISTER);
      if (!checkReStatus) return;
      const { phone, password } = this.state;
      this.register({ phone, password: encrypt(password) });
      //注册逻辑
    } else {
      this.setState({
        isLoginBtn: false,
      });
      this._createCode();
    }
  };

  /**
   * 校验表单
   * @return {Boolean} 当信息不完整时退出
   */
  checkData(type = 1) {
    if (!this.state.phone) {
      Toast.fail('请输入手机号码', 2);
      return false;
    }
    if (!this.state.password) {
      Toast.fail('请输入密码', 2);
      return false;
    }
    if (type === LOGIN_STATUS.REGISTER && this.state.passwordCheck !== this.state.password) {
      Toast.fail('两次密码不一致', 2);
      return false;
    }
    if (!/^1[3456789]\d{9}$/.test(this.state.phone)) {
      Toast.fail('请输入正确的手机号', 2);
      this.setState({ phoneError: true });
      return false;
    }
    if (!this.state.imgCode) {
      Toast.fail('请输入图形验证码', 2);
      return false;
    }
    if (!/^[a-zA-Z0-9]{4,5}$/.test(this.state.imgCode)) {
      Toast.fail('图形验证码不正确', 2);
      this.setState({ imgCodeError: true });
      return false;
    }
    console.log(this.state.imgCode, 'imageCode', this.state.code);
    if (this.state.imgCode.toLowerCase() !== this.state.code.toLowerCase()) {
      Toast.fail('图形验证码不正确', 2);
      this.setState({ imgCodeError: true });
      return false;
    }
    return true;
  }

  componentDidUpdate(prevProps, prevState) {
    // watch监听实时校验表单
    if (prevState.phone !== this.state.phone) {
      if (/^1[3456789]\d{9}$/.test(this.state.phone)) {
        this.setState({ phoneError: false });
      }
    }
    if (prevState.imgCode !== this.state.imgCode) {
      if (/^[0-9]{4}$/.test(this.state.imgCode)) {
        this.setState({ imgCodeError: false });
      }
    }
  }

  _createCode = () => {
    console.log(this, this.canvas);
    const ctx = this.canvas.getContext('2d');
    const chars = [
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      'a',
      'b',
      'c',
      'd',
      'e',
      'f',
      'g',
      'h',
      'j',
      'k',
      'l',
      'm',
      'n',
      'p',
      'q',
      'r',
      's',
      't',
      'u',
      'v',
      'w',
      'x',
      'y',
      'z',
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'J',
      'K',
      'L',
      'M',
      'N',
      'P',
      'Q',
      'R',
      'S',
      'T',
      'U',
      'V',
      'W',
      'X',
      'Y',
      'Z',
    ];
    let code = '';
    ctx.clearRect(0, 0, 80, 40);
    for (let i = 0; i < 4; i++) {
      const char = chars[randomNum(0, 57)];
      code += char;
      ctx.font = randomNum(20, 25) + 'px SimHei'; //设置字体随机大小
      ctx.fillStyle = '#99CCCC';
      ctx.textBaseline = 'middle';
      ctx.shadowOffsetX = randomNum(-3, 3);
      ctx.shadowOffsetY = randomNum(-3, 3);
      ctx.shadowBlur = randomNum(-3, 3);
      ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
      let x = (80 / 5) * (i + 1);
      let y = 40 / 2;
      let deg = randomNum(-25, 25);
      /**设置旋转角度和坐标原点**/
      ctx.translate(x, y);
      ctx.rotate((deg * Math.PI) / 180);
      ctx.fillText(char, 0, 0);
      /**恢复旋转角度和坐标原点**/
      ctx.rotate((-deg * Math.PI) / 180);
      ctx.translate(-x, -y);
    }
    this.setState({
      code,
    });
  };

  changeCaptcha = () => {
    this._createCode();
  };

  render() {
    const {
      phone,
      phoneIsFocus,
      phoneError,
      imgCode,
      codeImageUrl,
      isLoginBtn,
      imgCodeIsFocus,
      imgCodeError,
      passwordCheck,
      password,
      passwordIsFocus,
      passwordCheckIsFocus,
      codeText,
      isWait,
    } = this.state;
    return (
      <div className="login-bg">
        <div className="logo-wrap">
          <div className="logo"></div>
          <div className="welcome-wrap">
            <div className="hello">您好!</div>
            <div className="welcome">
              欢迎来到<span>云之间</span>
            </div>
          </div>
        </div>
        <div className="form-wraper">
          <div className={classNames('input-wrap')}>
            <CSSTransition in={phone.length > 0} timeout={400} classNames="fade" unmountOnExit>
              <span>手机号</span>
            </CSSTransition>
            <CSSTransition in={phone.length > 0} timeout={400} classNames="input">
              <input
                className={phoneError ? 'error' : ''}
                value={phone}
                onChange={e => {
                  if (e.target.value.length <= 11) {
                    this.setState({ phone: e.target.value });
                  }
                }}
                onFocus={() => {
                  this.setState({ phoneIsFocus: true });
                }}
                onBlur={() => {
                  this.setState({ phoneIsFocus: false });
                }}
                type="text"
                placeholder="请输入手机号"
              />
            </CSSTransition>
          </div>
          <Line show={phoneIsFocus} />
          <div className={classNames('input-wrap-flex', 'margin-top-20')}>
            <div className="left">
              <CSSTransition in={password.length > 0} timeout={400} classNames="input">
                <input
                  value={password}
                  type="password"
                  onChange={e => {
                    this.setState({ password: e.target.value });
                  }}
                  onFocus={() => {
                    this.setState({ passwordIsFocus: true });
                  }}
                  onBlur={() => {
                    this.setState({ passwordIsFocus: false });
                  }}
                  placeholder="请输入密码"
                />
              </CSSTransition>
            </div>
          </div>
          <Line show={passwordIsFocus} />
          {!isLoginBtn ? (
            <>
              <div className={classNames('input-wrap-flex', 'margin-top-20')}>
                <div className="left">
                  <CSSTransition in={passwordCheck.length > 0} timeout={400} classNames="input">
                    <input
                      value={passwordCheck}
                      type="password"
                      onChange={e => {
                        this.setState({ passwordCheck: e.target.value });
                      }}
                      onFocus={() => {
                        this.setState({ passwordCheckIsFocus: true });
                      }}
                      onBlur={() => {
                        this.setState({ passwordCheckIsFocus: false });
                      }}
                      placeholder="请输入密码"
                    />
                  </CSSTransition>
                </div>
              </div>
              <Line show={passwordCheckIsFocus} />
            </>
          ) : (
            ''
          )}
          <div className={classNames('input-wrap-flex', 'margin-top-20')}>
            <div className="left">
              <CSSTransition in={imgCode.length > 0} timeout={400} classNames="fade" unmountOnExit>
                <span>图形验证码</span>
              </CSSTransition>
              <CSSTransition in={imgCode.length > 0} timeout={400} classNames="input">
                <input
                  className={imgCodeError ? 'error' : ''}
                  value={imgCode}
                  onChange={e => {
                    this.setState({ imgCode: e.target.value });
                  }}
                  onFocus={() => {
                    this.setState({ imgCodeIsFocus: true });
                  }}
                  onBlur={() => {
                    this.setState({ imgCodeIsFocus: false });
                  }}
                  type="text"
                  placeholder="请输入图像验证码"
                />
              </CSSTransition>
            </div>
            <div className="right">
              <canvas
                onClick={this.changeCaptcha}
                width="80"
                height="40"
                ref={el => (this.canvas = el)}
              />
            </div>
          </div>
          <Line show={imgCodeIsFocus} />
        </div>
        <div className="login-wrap">
          <div
            className={isLoginBtn ? 'login' : 'login btn-disabled'}
            onClick={() => this.submit(LOGIN_STATUS.LOGIN)}
          >
            登录
          </div>
          <div
            className={isLoginBtn ? 'login register btn-disabled' : 'login register'}
            onClick={() => this.submit(LOGIN_STATUS.REGISTER)}
          >
            注册
          </div>
        </div>
        <p
          className="agree-wrap"
          onClick={e => {
            this.showProtocol();
          }}
        >
          登录或注册即代表您已同意<span className="agree">《用户注册协议》</span>
        </p>
        {/*----协议----*/}
        <Modal
          popup
          visible={this.state.visible}
          animationType="slide-up"
          className="modal-service"
          platform={'android'}
          onClose={this.onClose('visible')}
          footer={[
            {
              text: '确 定',
              onPress: () => {
                console.log('ok');
                this.onClose('visible')();
              },
            },
          ]}
        >
          <div className="register-text" style={{ height: 360 }}>
            <p>
              审慎阅读】您在申请注册流程中点击同意前，应当认真阅读以下协议。请您务必审慎阅读、充分理解协议中各条款内容，其中包括：
            </p>
            <p>1、与您约定免除或限制责任的条款；</p>
            <p>2、与您约定法律适用和管辖的条款；</p>
            <p>
              3、其他以粗体下划线标识的重要条款。 如您对协议有任何疑问，可向云之间 平台客服咨询。
            </p>
          </div>
        </Modal>
      </div>
    );
  }
}

// 分割线动画组件
class Line extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <div className="line-wrap">
        <CSSTransition in={this.props.show} timeout={500} classNames="line">
          <div className="line"></div>
        </CSSTransition>
      </div>
    );
  }
}
export default LoginNew;
